﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication11.Models;

namespace WebApplication11.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(DB.Books);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult CreateBook()
        {
            Books model = new Books();
            return View(model);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult CreateBook(Books NewBook)
        {
            if (ModelState.IsValid)
            {
                bool result = DB.CreateBook(NewBook);
                if (!result)
                {
                    ViewBag.ISBNError = "ISBN already exists in the database";
                    return View(NewBook);
                }
                return RedirectToAction("Index");
            }
            else return View(NewBook);
        }

        public ActionResult EditBook(int id)
        {
            Books model = DB.Books.FirstOrDefault(x => x.Id == id);
            if (model != null) return View(model);
            else return RedirectToAction("Home", "Index");
        }

        [HttpPost]
        public ActionResult EditBook(Books model)
        {
            DB.Books[DB.Books.IndexOf(DB.Books.FirstOrDefault(x => x.Id == model.Id))] = model;
            return RedirectToAction("Index", new { id = model.Id });
        }

        public ActionResult Delete(int id)
        {
            DB.Books.RemoveAll(x => x.Id == id);
            return RedirectToAction("Index");
        }
    }
}